package com.qipay.utils;




import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.SignatureException;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class MD5Util {

	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname))
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes()));
			else
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes(charsetname)));
		} catch (Exception exception) {
		}
		return resultString;
	}

	public static byte[] MD5Encode0(String origin, String charsetname) {

		String resultString = null;
		byte[] md5bytes = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname))
				md5bytes = md.digest(resultString.getBytes());
			else
				md5bytes = md.digest(resultString.getBytes(charsetname));
		} catch (Exception exception) {
		}
		return md5bytes;
	}


	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	public static String getSign(Map<String,Object> maps, String key){
		SortedMap<String, Object> params=new TreeMap<String, Object>();
		for (String mapKey : maps.keySet()) {
			params.put(mapKey, maps.get(mapKey));
		}

		StringBuilder sb=new StringBuilder();
		for (String keyItem : params.keySet()) {
			if(params.get(keyItem)!=null&&!params.get(keyItem).toString().equals("")
					&&!keyItem.equals("sign")&&!keyItem.equals("Sign")&&
					!keyItem.equals("signature")&&!keyItem.equals("signData")){
				sb.append(keyItem + "=" + params.get(keyItem).toString() + "&");
			}
		}
		sb.append("key=" +key);
		String bunch=sb.toString();
		String sign = MD5Util.MD5Encode(bunch,"UTF-8");
		return sign;
	}


	/**
	 签名字符串

	 @param text 需要签名的字符串
	 @param input_charset 编码格式
	 @return 签名结果
	 */
	public static String sign(String text, String input_charset)
	{
		System.out.println(text);
		return DigestUtils.md5Hex(getContentBytes(text, input_charset)).toUpperCase();
	}

	/**
	 签名字符串

	 @param text 需要签名的字符串
	 @param sign 签名结果
	 @param input_charset 编码格式
	 @return 签名结果
	 */
	public static boolean verify(String text, String sign, String input_charset)
	{
		String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
		if (mysign.equals(sign)) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 @param content
	 @param charset
	 @return
	 @throws SignatureException
	 @throws UnsupportedEncodingException
	 */
	private static byte[] getContentBytes(String content, String charset)
	{
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		}
		catch (UnsupportedEncodingException e) {
			throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}


}
